import React, {useState} from 'react'
import styles from "./index.module.less"; // 引入样式
import { Button, Form, Input, message } from 'antd';
import { LockOutlined, UserOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';

import { useAppDispatch } from '@/hooks';  // 引入统一封装的dispatch
import { postLoginAsync } from '@/store/slice/auth'; // 引入store的接口


// 引入仓库
import { useSelectorAuth } from '@/store/slice/auth';

function Login() {
  const navigate = useNavigate()

  // - 通过useDispatch获得dispatch方法
  const dispatch = useAppDispatch();

  // 实现 不能触发第二次
  const {isLoading} = useSelectorAuth();
  
  // 请求登录接口
  const handleFinish =  async(values:any)=>{
    console.log(values); // 输入的username和password  是一个对象
    try{
      const result:any = await dispatch(postLoginAsync(values));
      console.log(result);// 请求成功的结果
      message.success(result.message)
      navigate("/");
    }catch(err){
    }
  }


  return (
    <div className={styles.login}>
      <div>
        <h1>尚医通管理系统</h1>
        <Form
          name="normal_login"
          className="login-form"
          onFinish={handleFinish}
          initialValues={{username:'admin',password:'111111'}}
        >
          <Form.Item
            name="username"
            rules={[{ required: true, message: '请输入管理员账号' }]}
          >
            {/* initialValues表单默认值  类型是对象  */}
            <Input prefix={<UserOutlined className="site-form-item-icon" />} placeholder="请输入管理员账号" />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '请输入管理员密码！' }]}
          >
            <Input
              prefix={<LockOutlined className="site-form-item-icon" />}
              type="password"
              placeholder="请输入管理员密码"
            />
          </Form.Item>
          <Form.Item>
            {/* 限制不能一直点击登录登录   */}
            <Button type="primary" loading={isLoading} htmlType="submit" className="login-form-button">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}

export default Login